package beans;

import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import dao.DAOClient;
import dao.DAOFactory;

@ManagedBean
public class Connexion {

	/**
	 * Identifiant pour la connection
	 */
	private String identifiant;
	
	/**
	 * Mot de passe pour la connection
	 */
	private String password;
	
	/**
	 * Connexion
	 * @return
	 * @throws IOException
	 */
	public String connecter() {
		
		DAOClient dao = DAOFactory.getDAOClient();  
		
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		
		//Recuperation du mot de passe et comparaison
		Client c = dao.find(identifiant);
		if( c!=null && c.getMdp().equals(password)){
			HttpServletRequest request = (HttpServletRequest)context.getRequest();
			request.getSession().setAttribute("idUser", c.getId());
			request.getSession().setAttribute("nomUser", c.getNom());
			request.getSession().setAttribute("estAdmin", c.isAdmin());
			
			//Si admin, on va au panneau d'admin
			if(c.isAdmin()){
				return "/admin/adminIndex.xhtml?faces-redirect=true";
			}else{
				return "/index.xhtml?faces-redirect=true";			
			}
			
		}else{
			//Echec de connexion
			return "index.xhtml";
		}
	}
	
	/**
	 * Deconnexion
	 * @return
	 */
	public String deconnecter(){
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		HttpServletRequest request = (HttpServletRequest)context.getRequest();
		request.getSession().removeAttribute("idUser");
		request.getSession().removeAttribute("nomUser");
		request.getSession().removeAttribute("estAdmin");
		return "index.xhtml";
	}

	public String getIdentifiant() {
		return identifiant;
	}

	public void setIdentifiant(String identifiant) {
		this.identifiant = identifiant;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
